package defectsim.agents;

import java.io.IOException;

import repast.simphony.parameter.Parameters;
import repast.simphony.random.RandomHelper;
import defectsim.Globals;
import defectsim.SimulationEnvironment;
import defectsim.agents.DefectFactory.DefectType;

public class PointDefectSource extends DefectAgent{

	private SimulationEnvironment environment = SimulationEnvironment.getInstance();
	
	private int nPointDefects;
	private double boxLength;
	private int gridSize;
	private int nSlipPlanes;
	private double unitBurgersVector;
	private double pointDefectSize;
	
	public PointDefectSource(){
		Parameters p = environment.getParameters();
		this.boxLength = (Double)p.getValue("spacelength");
		this.gridSize = (Integer)p.getValue("gridsize");
		this.nPointDefects = (Integer)p.getValue("nopointdefects");
		this.unitBurgersVector = environment.getMaterial().getBurgersVector()* Globals.NANOMETER_TO_MICROMETER;
		this.nSlipPlanes = (int) (boxLength / unitBurgersVector);
		this.pointDefectSize = 1000.0 * this.unitBurgersVector;
	}
	


	@Override
	public void percept() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void mentalUpdate() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void act() {
		if (environment.getCurrentTick() == 1.0) 
			this.createPointDefectsByBurgers(nPointDefects);
		
	}

//	private void createPointDefects(int nPointDefects){
//		double gridScale = gridSize / boxLength;
//		for (int i = 0; i < nPointDefects; i++){
//			PointDefect pointDefect = (PointDefect) DefectFactory.createDefect(DefectType.PointDefect);
//			double dx = findRandomLocation(0.0, boxLength);
//			double dy = findRandomLocation(0.0, boxLength);
//			pointDefect.setX(dx);
//			pointDefect.setY(dy);
//			pointDefect.setLocationGridX((int)(dx * gridScale));
//			pointDefect.setLocationGridY((int)(dy * gridScale));
//			environment.add(pointDefect);
//		}
//	}
	
	private void createPointDefectsByBurgers(int nPointDefects){
		double gridScale = gridSize / boxLength;
		for (int i = 0; i < nPointDefects; i++){
			PointDefect pointDefect = (PointDefect) DefectFactory.createDefect(DefectType.PointDefect);
			double dx = unitBurgersVector * findRandomLocation(1, nSlipPlanes - 1);
			double dy = unitBurgersVector * findRandomLocation(1, nSlipPlanes - 1);
			pointDefect.setX(dx);
			pointDefect.setY(dy);
			pointDefect.setLocationGridX((int)(dx * gridScale));
			pointDefect.setLocationGridY((int)(dy * gridScale));
			pointDefect.setPointDefectSize(pointDefectSize);
			environment.add(pointDefect);
		}
	}

//	private double findRandomLocation(double minimum, double maximum) {
//		return RandomHelper.nextDoubleFromTo(minimum, maximum);
//	}

	private int findRandomLocation(int minimum, int maximum) {
		return RandomHelper.nextIntFromTo(minimum, maximum);
	}
}
